package com.qd.system.service.login;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.sys.domain.entity.login.LoginUserDTO;
import com.qd.system.mapper.LoginUserMapper;
import com.qd.system.model.LoginUser;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.org.OrgService;
import com.qd.system.service.user.UserOperatorService;
import com.qd.system.util.FileConfirmUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LoginUserService extends BaseService<LoginUserMapper, LoginUser> {
    private static final String PREFIX_ID = "sys_login_user_personId_{0}";
    private static final String PREFIX_ACCOUNT = "sys_login_user_account_{0}";
    private final RedisTemplateUtil<LoginUser> redisTemplateUtil;
    private final OrgService orgService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public LoginUserDTO save(LoginUserDTO dto) {
        checkUnique(dto);
        final LoginUser model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public LoginUserDTO update(LoginUserDTO dto) {
        checkUnique(dto);
        final LoginUser historyModel = Optional.ofNullable(getById(dto.getPersonId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final LoginUser model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param personId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String personId) {
        final LoginUser model = Optional.ofNullable(getById(personId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(personId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        List<LoginUser> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(LoginUserDTO dto) {
        final QueryWrapper<LoginUser> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param personId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String personId) {
        boolean exists = false;
        if (StringUtils.hasLength(personId)) {
            final LoginUser model = getById(personId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param personId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public LoginUser getById(String personId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, personId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(personId), LoginUser.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param personId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public LoginUserDTO getByIdDto(String personId) {
        final LoginUser model = getById(personId);
        if (null != model) {
            return modelToDto(model);
        }
        return null;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public LoginUser getOne(LoginUserDTO dto) {
        final QueryWrapper<LoginUser> queryWrapper = createQueryWrapper(dto);
        final LoginUser model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public LoginUserDTO getOneDto(LoginUserDTO dto) {
        final LoginUser model = getOne(dto);
        if (null == model) {
            return null;
        }
        final LoginUserDTO newDto = modelToDto(model);
        model.freeData();
        return newDto;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<LoginUser> getList(LoginUserDTO dto) {
        final QueryWrapper<LoginUser> queryWrapper = createQueryWrapper(dto);
        final List<LoginUser> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<LoginUserDTO> getListDto(LoginUserDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<LoginUserDTO> page(Page<LoginUser> page, LoginUserDTO dto) {
        final QueryWrapper<LoginUser> queryWrapper = createQueryWrapper(dto, "log.");
        UserOperatorService.buildOrgIds(dto, queryWrapper, "o.");
        page.setSearchCount(false);
        final Long total = getBaseMapper().pageCount(queryWrapper);
        final IPage<LoginUserDTO> iPage = getBaseMapper().page(page, queryWrapper);
        iPage.setTotal(null == total ? 0 : total);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 根据唯一性索引获得数据
     * <p>
     * param account
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public LoginUser getUniqueByAccount(String account) {
        final QueryWrapper<LoginUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ACCOUNT, account);
        final LoginUser model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), LoginUser.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据登录名或者手机号查询用户信息
     *
     * @param mobile 手机号
     * @return 用户信息
     */
    @Transactional(readOnly = true)
    public LoginUser getLoginUserByMobile(String mobile) {
        final QueryWrapper<LoginUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        try {
            return super.getOne(queryWrapper, true);

        } catch (MybatisPlusException e) {
            throw new ApiException("手机号不唯一");
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    private void checkUnique(LoginUserDTO dto) {
        final LoginUser model = getUniqueByAccount(dto.getAccount());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(LoginUserDTO dto, LoginUser model) {
        if (!StringUtils.hasLength(dto.getPersonId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getPersonId().equals(model.getPersonId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    @Transactional(readOnly = true)
    public void clearCache(LoginUser model) {
        final String idKey = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getPersonId());
        String accountKey = null;
        if (StringUtils.hasLength(model.getAccount())) {
            accountKey = RedisTemplateUtil.getRedisCacheKey(PREFIX_ACCOUNT, model.getAccount());
        } else {
            final LoginUser user = getById(model.getPersonId());
            if (user != null) {
                accountKey = RedisTemplateUtil.getRedisCacheKey(PREFIX_ACCOUNT, user.getAccount());
                user.freeData();
            }
        }
        redisTemplateUtil.deleteByKey(idKey);
        if (StringUtils.hasLength(accountKey)) {
            redisTemplateUtil.deleteByKey(accountKey);
        }
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<LoginUser> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        list.forEach(this::clearCache);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public LoginUserDTO modelToDto(LoginUser model) {
        if (null == model) {
            return null;
        }
        final LoginUserDTO dto = new LoginUserDTO();
        dto.setPersonId(model.getPersonId());
        dto.setAccount(model.getAccount());
        dto.setPassword(model.getPassword());
        dto.setPersonName(model.getPersonName());
        dto.setIdCard(model.getIdCard());
        dto.setMobile(model.getMobile());
        dto.setPersonType(model.getPersonType());
        dto.setSex(model.getSex());
        dto.setEmail(model.getEmail());
        dto.setAvatar(model.getAvatar());
        dto.setState(model.getState());
        dto.setLoginIp(model.getLoginIp());
        dto.setLoginDate(model.getLoginDate());
        dto.setOrgId(model.getOrgId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public LoginUser dtoToModel(LoginUserDTO dto) {
        if (null == dto) {
            return null;
        }
        final LoginUser model = new LoginUser();
        model.setPersonId(dto.getPersonId());
        model.setAccount(dto.getAccount());
        model.setPassword(dto.getPassword());
        model.setPersonName(dto.getPersonName());
        model.setIdCard(dto.getIdCard());
        model.setMobile(dto.getMobile());
        model.setPersonType(dto.getPersonType());
        model.setSex(dto.getSex());
        model.setEmail(dto.getEmail());
        model.setAvatar(dto.getAvatar());
        model.setState(dto.getState());
        model.setLoginIp(dto.getLoginIp());
        model.setLoginDate(dto.getLoginDate());
        model.setOrgId(dto.getOrgId());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(LoginUserDTO dto) {
        dto.setOrgIdDisplay(orgService.idToDisplay(dto.getOrgId()));
        dto.setSexDisplay(MbUtil.idToDisplay(dto.getSex()));
        dto.setPersonTypeDisplay(MbUtil.idToDisplay(dto.getPersonType()));
        dto.setStateDisplay(MbUtil.idToDisplay(dto.getState()));
        dto.setAvatarDisplay(FileConfirmUtil.getImageFile(dto.getAvatar()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<LoginUserDTO> modelToDtoList(List<LoginUser> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<LoginUser> dtoToModelList(List<LoginUserDTO> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<LoginUser> createQueryWrapper(LoginUserDTO dto, String tableAlias) {
        final QueryWrapper<LoginUser> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getAccount())) {
                queryWrapper.eq(tableAlias + "account", dto.getAccount());
            }
            if (StringUtils.hasLength(dto.getPersonName())) {
                queryWrapper.like(tableAlias + "person_name", dto.getPersonName());
            }
            if (StringUtils.hasLength(dto.getIdCard())) {
                queryWrapper.eq(tableAlias + "id_card", dto.getIdCard());
            }
            if (StringUtils.hasLength(dto.getMobile())) {
                queryWrapper.eq(tableAlias + "mobile", dto.getMobile());
            }
            if (StringUtils.hasLength(dto.getPersonType())) {
                queryWrapper.eq(tableAlias + "person_type", dto.getPersonType());
            }
            if (StringUtils.hasLength(dto.getSex())) {
                queryWrapper.eq(tableAlias + "sex", dto.getSex());
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + "org_id", dto.getOrgId());
            }
        }
        return queryWrapper;
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<LoginUser> createQueryWrapper(LoginUserDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<LoginUser> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<LoginUser> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(LoginUser::getPersonId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 更具用户名查询用户信息
     *
     * @param userName 用户名
     * @return 用户信息
     */
    public LoginUser selectUserByUserName(String userName) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ACCOUNT, userName);
        final LoginUserDTO queryDto = new LoginUserDTO();
        queryDto.setAccount(userName);
        final QueryWrapper<LoginUser> queryWrapper = createQueryWrapper(queryDto);
        try {
            final LoginUser loginUser = redisTemplateUtil.get(new CacheKey().setKey(key), () -> getOne(queryWrapper), LoginUser.class);
            queryDto.freeData();
            queryWrapper.clear();
            return loginUser;
        } catch (Exception e) {
            throw new ApiException("账号不唯一");
        }

    }

    /**
     * 更具用户名查询用户信息
     *
     * @param userName 用户名
     * @return 用户信息
     */
    public LoginUserDTO selectUserByUserNameDto(String userName) {
        final LoginUser loginUser = selectUserByUserName(userName);
        if (null == loginUser) {
            return null;
        }
        return modelToDto(loginUser);
    }

    /**
     * 根据机构ID查询登录用户列表
     *
     * @param orgId 机构ID
     * @return 用户列表
     */
    public List<LoginUser> getListByOrgId(String orgId) {
        final LoginUserDTO queryDto = new LoginUserDTO();
        queryDto.setOrgId(orgId);
        final QueryWrapper<LoginUser> queryWrapper = createQueryWrapper(queryDto);
        final List<LoginUser> list = list(queryWrapper);
        queryWrapper.clear();
        queryDto.freeData();
        return list;
    }

    /**
     * 判断账号唯一性
     *
     * @param LoginUserDTO 登录信息
     * @return 存在 or 不存在
     */
    public Boolean checkAccountUnique(LoginUserDTO LoginUserDTO) {
        return isExistsByUpdate(LoginUserDTO);
    }

    /**
     * 判断身份证号唯一性
     *
     * @param LoginUserDTO 登录信息
     * @return 存在 or 不存在
     */
    public boolean checkIdCardUnique(LoginUserDTO LoginUserDTO) {
        return isExistsByUpdate(LoginUserDTO);
    }

    /**
     * 根据条件判断是否存在
     *
     * @param queryDto 查询参数
     * @return 存在 or 不存在
     */
    private boolean isExistsByUpdate(LoginUserDTO queryDto) {
        final LoginUser loginUser = getOne(queryDto);
        boolean exists = false;
        if (null != loginUser) {
            if (StringUtils.hasLength(loginUser.getPersonId())) {
                exists = !queryDto.getPersonId().equals(loginUser.getPersonId());
            } else {
                exists = true;
            }
            loginUser.freeData();
        }
        return exists;
    }

    /**
     * 判断用户登录信息
     *
     * @param personId 用户ID
     */
    @Transactional(readOnly = true)
    public void checkLoginUser(String personId) {
        if (StringUtils.hasLength(personId)) {
            final LoginUser loginUser = getById(personId);
            if (loginUser == null) {
                throw new ApiException("用户登录信息不存在");
            }
            loginUser.freeData();
        }
    }

    /**
     * 获得人员名称
     *
     * @param personId 人员ID
     * @return 姓名
     */
    @Transactional(readOnly = true)
    public String idToDisplay(String personId) {
        String display = "";
        if (StringUtils.hasLength(personId)) {
            final LoginUser loginUser = getById(personId);
            display = Optional.ofNullable(loginUser).map(LoginUser::getPersonName).orElse("");
        }
        return display;
    }
}